package com.erp.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.shop.domain.ErpShopBindRecord;
import com.erp.shop.domain.bo.ErpSellerStoreEmpowerBo;
import com.erp.shop.domain.dto.ErpSellerStoreSelfEvaluationDto;
import com.erp.shop.mapper.ErpSellerStoreEmpowerMapper;
import com.erp.shop.mapper.ErpShopBindRecordMapper;
import com.erp.shop.service.IErpSellerStoreEmpowerService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import com.ruoyi.shop.api.domain.vo.ErpSellerStoreEmpowerVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * 卖家店铺授权Service业务层处理
 *
 * @author erp
 * @date 2023-03-24
 */
@RequiredArgsConstructor
@Service
public class ErpSellerStoreEmpowerServiceImpl implements IErpSellerStoreEmpowerService {

    private final ErpSellerStoreEmpowerMapper baseMapper;
    private final ErpShopBindRecordMapper shopBindRecordMapper;
//    private final ErpSellerOrderMapper sellerOrderMapper;
//    private final ErpAdvertisementLogMapper advertisementLogMapper;
//    private final ErpOrderProductStatisticsMapper statisticsMapper;
//    private final ErpUserInfoMapper userInfoMapper;
//    private final ErpOrderInfoStatisticsMapper orderInfoStatisticsMapper;
//    private final ErpChildOrderStatisticsMapper childOrderStatisticsMapper;
//    private final ErpStoreUserAssociationMapper storeUserAssociationMapper;
//    private final ErpSellerStoreProductMapper erpSellerStoreProductMapper;

//    private final AEConfig aeConfig;

    @Override
    public TableDataInfo<ErpSellerStoreSelfEvaluationDto> getSelfOperationEvaluation(PageQuery page, ErpSellerStoreSelfEvaluationDto dto) {

        Page<ErpSellerStoreSelfEvaluationDto> storeEmpowerList = baseMapper.selfOperationAuth(page.build(), dto);

        for (ErpSellerStoreSelfEvaluationDto storeEmpower : storeEmpowerList.getRecords()) {
            // TODO 访问统计接口获取数据
//            String realPurchase = baseMapper.getSelfOperationEvaluation(storeEmpower);
//            if (realPurchase == null) {
//                realPurchase = "0.00";
//            }
//            storeEmpower.setRealProfit(realPurchase);
//            // 获取刷单利润
//            String evaProfit = baseMapper.getEvaluationProfit(storeEmpower.getStoreId());
//            if (evaProfit == null) {
//                evaProfit = "0.00";
//            }
//            storeEmpower.setEvaProfit(evaProfit);
        }
        return TableDataInfo.build(storeEmpowerList);
    }

    /**
     * 查询卖家店铺授权
     */
    @Override
    public ErpSellerStoreEmpowerVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询卖家店铺授权列表
     */
    @Override
    public TableDataInfo<ErpSellerStoreEmpowerVo> queryPageList(ErpSellerStoreEmpowerBo bo, PageQuery pageQuery) {
        Long userId = SecurityUtils.getUserId();
        bo.setUserId(userId);
        LambdaQueryWrapper<ErpSellerStoreEmpower> lqw = buildQueryWrapper(bo);
        Page<ErpSellerStoreEmpowerVo> result = new Page<>();
        if (userId.toString().equals("1677136581263863809") || userId.toString().equals("1656928429061378049")) {
            result = baseMapper.selectAllVoPage(pageQuery.build());
        } else {
            result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        }
        List<ErpSellerStoreEmpower> list = new ArrayList<ErpSellerStoreEmpower>();
        result.getRecords().forEach(vo -> {
            Date expireTime = vo.getExpireTime();
            // 判断是否过期
            if (expireTime != null) {
                if (expireTime.before(new Date())) {
                    vo.setIsEmpower("2");
                    ErpSellerStoreEmpower empower = new ErpSellerStoreEmpower();
                    empower.setId(vo.getId());
                    empower.setIsEmpower("2");
                    list.add(empower);
                }
            }
        });
        if (list.size() > 0)
            baseMapper.updateBatchById(list);
        return TableDataInfo.build(result);
    }

    /**
     * 查询卖家店铺授权列表
     */
    @Override
    public List<ErpSellerStoreEmpowerVo> queryList(ErpSellerStoreEmpowerBo bo) {
        if (bo.getUserId() == null) {
            Long userId = SecurityUtils.getUserId();
            bo.setUserId(userId);
        }
        if (bo.getIsEmpower() == null) {
            bo.setIsEmpower("1");
        }
        LambdaQueryWrapper<ErpSellerStoreEmpower> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpSellerStoreEmpower> buildQueryWrapper(ErpSellerStoreEmpowerBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpSellerStoreEmpower> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getStoreName()), ErpSellerStoreEmpower::getStoreName, bo.getStoreName());
        lqw.eq(StringUtils.isNotBlank(bo.getStoreEmail()), ErpSellerStoreEmpower::getStoreEmail, bo.getStoreEmail());
        lqw.like(StringUtils.isNotBlank(bo.getStoreUserName()), ErpSellerStoreEmpower::getStoreUserName,
                bo.getStoreUserName());
        lqw.eq(StringUtils.isNotBlank(bo.getStorePassWord()), ErpSellerStoreEmpower::getStorePassWord,
                bo.getStorePassWord());
        lqw.eq(StringUtils.isNotBlank(bo.getStorePhone()), ErpSellerStoreEmpower::getStorePhone, bo.getStorePhone());
        lqw.eq(StringUtils.isNotBlank(bo.getIsEmpower()), ErpSellerStoreEmpower::getIsEmpower, bo.getIsEmpower());
        lqw.eq(bo.getEmpowerTime() != null, ErpSellerStoreEmpower::getEmpowerTime, bo.getEmpowerTime());
        lqw.eq(bo.getUserId() != null && bo.getUserId() != 1L, ErpSellerStoreEmpower::getUserId, bo.getUserId());
        lqw.eq(bo.getIsRetuenFreight() != null, ErpSellerStoreEmpower::getIsRetuenFreight, bo.getIsRetuenFreight());
        lqw.eq(StringUtils.isNotBlank(bo.getStoreType()), ErpSellerStoreEmpower::getStoreType, bo.getStoreType());
        return lqw;
    }

    /**
     * 新增卖家店铺授权
     */
    @Override
    public Boolean insertByBo(ErpSellerStoreEmpowerBo bo) {
        ErpSellerStoreEmpower add = BeanUtil.toBean(bo, ErpSellerStoreEmpower.class);

        add.setUserId(null);
        add.setIsEmpower("0");

        validEntityBeforeSave(add);
        boolean flag = false;

        // 查看是否有删除的店铺，如果是删除的那么直接修改为正常并绑定到该用户下
        ErpSellerStoreEmpower empower = baseMapper.selectDelEmpowerByUserName(add.getStoreUserName());
        if (empower != null) {
            add.setId(empower.getId());
            add.setUserId(null);
            flag = baseMapper.updateDelEmpower(add) > 0;

            // TODO 修改在线商品的数据到新账户下
//            LambdaUpdateWrapper<ErpSellerStoreProduct> luw = Wrappers.lambdaUpdate();
//            luw.eq(ErpSellerStoreProduct::getStoreId, empower.getId());
//            luw.set(ErpSellerStoreProduct::getCreateBy, LoginHelper.getUserId());
//            luw.set(ErpSellerStoreProduct::getUpdateBy, LoginHelper.getUserId());
//            erpSellerStoreProductMapper.update(null, luw);
        } else {
            flag = baseMapper.insert(add) > 0;
        }

        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改卖家店铺授权
     */
    @Override
    public Boolean updateByBo(ErpSellerStoreEmpowerBo bo) {
        ErpSellerStoreEmpower update = BeanUtil.toBean(bo, ErpSellerStoreEmpower.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpSellerStoreEmpower entity) {
        // TODO 做一些数据校验,如唯一约束

        // 查看店铺是否已经绑定
        String storeUserName = entity.getStoreUserName();
        LambdaQueryWrapper<ErpSellerStoreEmpower> lqw = Wrappers.lambdaQuery();
        lqw.eq(ErpSellerStoreEmpower::getStoreUserName, storeUserName);
        lqw.ne(ErpSellerStoreEmpower::getUserId, entity.getUserId());
        List<ErpSellerStoreEmpower> selectList = baseMapper.selectList(lqw);
        if (selectList != null && selectList.size() > 0) {
            throw new RuntimeException("店铺已绑定");
        }

        // 查看是否是新增，如果是新增，看是不是新增的已经有的店铺
        if (entity.getId() == null) {
            // 查看是否有
            lqw = Wrappers.lambdaQuery();
            lqw.eq(ErpSellerStoreEmpower::getStoreUserName, storeUserName);
            lqw.eq(ErpSellerStoreEmpower::getUserId, entity.getUserId());
            selectList = baseMapper.selectList(lqw);
            if (selectList != null && selectList.size() > 0) {
                throw new RuntimeException("店铺已绑定");
            }
        }

    }

    /**
     * 批量删除卖家店铺授权
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Long queryBySellerLoginId(String sellerLoginId) {
        return baseMapper.queryBySellerLoginId(sellerLoginId);
    }

    @Override
    public Long queryUserIdBySellerLoginId(String sellerLoginId) {

        return (Long) baseMapper.selectMaps(new LambdaQueryWrapper<ErpSellerStoreEmpower>()
                .eq(ErpSellerStoreEmpower::getStoreUserName, sellerLoginId)).get(0).get("user_id");
    }

    /**
     * 获取已经授权的商家
     *
     * @return
     */
    @Override
    public List<ErpSellerStoreEmpower> getEmpowerStore() {
        // 获取授权商家
        return baseMapper.getIsEmpowerStore();
    }

    @Override
    public String getStoreNameByUserName(String storeUserName) {
        return (String) baseMapper.selectMaps(new LambdaQueryWrapper<ErpSellerStoreEmpower>()
                .eq(ErpSellerStoreEmpower::getStoreUserName, storeUserName)).get(0).get("store_name");
    }

    @Override
    public ErpSellerStoreEmpower queryByStoreId(Long storeId) {
        return baseMapper.selectById(storeId);
    }

    @Override
    public ErpSellerStoreEmpower queryByStoreUserName(String storeUserName) {
        return baseMapper.selectOne(new LambdaQueryWrapper<ErpSellerStoreEmpower>()
                .eq(ErpSellerStoreEmpower::getStoreUserName, storeUserName).last("limit 1"));
    }

    @Override
    public Long getStoreIdByStoreUseName(String sellerLoginId) {
        ErpSellerStoreEmpowerVo storeEmpower = baseMapper.selectVoOne(new LambdaQueryWrapper<ErpSellerStoreEmpower>()
                .eq(ErpSellerStoreEmpower::getStoreUserName, sellerLoginId).last("limit 1"));
        return storeEmpower.getId();
    }

    @Override
    public List<String> getBehindErpPayStoreList() {
        return baseMapper.getBehindErpPayStoreList();
    }

    /**
     * 查询有效授权店铺信息
     * @param sellerLoginId
     * @return
     */
    @Override
    public ErpSellerStoreEmpower selectEmpowerByUserName(String sellerLoginId) {
        return baseMapper.selectEmpowerByUserName(sellerLoginId);
    }

    /**
     * 查询所有店铺授权信息
     * @param sellerLoginId
     * @return
     */
    @Override
    public List<ErpSellerStoreEmpower> selectListByStoreUserName(String sellerLoginId){
        return baseMapper.selectListByStoreUserName(sellerLoginId);
    }

    @Override
    public List<ErpSellerStoreEmpower> getAllStoreEmpower() {
        return baseMapper.getIsEmpowerStore();
    }

    @Override
    public boolean updateStorePassWord(String storeUserName, String storePassWord) {
        ErpSellerStoreEmpower storeEmpower = new ErpSellerStoreEmpower();
        storeEmpower.setStorePassWord(storePassWord);
        if (baseMapper.update(storeEmpower,
                new LambdaQueryWrapper<ErpSellerStoreEmpower>().eq(ErpSellerStoreEmpower::getStoreUserName, storeUserName)) > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public ErpSellerStoreEmpower getEmpowerStoreByUserNick(String userNick) {
        return baseMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerStoreEmpower>().eq(ErpSellerStoreEmpower::getStoreUserName, userNick));
    }

    @Override
    public R<Object> storeDiagnosis(Long storeId) {
        RestTemplate restTemplate = new RestTemplate();
        // TODO 发往ae模块
//        ResponseEntity<String> forEntity = restTemplate
//                .getForEntity(aeConfig.getEndpoint() + "/erp/erpSellerStore/storeDiagnosis?storeId=" + storeId, String.class);
//        String body = (String) forEntity.getBody();
//        System.out.println(body);
//        return R.ok(body);
        return R.ok();
    }

    @Override
    public List<ErpSellerStoreEmpower> getAutoStoreInfo() {
        //找还生效的，且店铺类型 为自动化代运营的
        return baseMapper.selectList(
                new LambdaQueryWrapper<ErpSellerStoreEmpower>()
                        .eq(ErpSellerStoreEmpower::getDelFlag, 0)
                        .eq(ErpSellerStoreEmpower::getStoreType, 4));
    }

    @Override
    public R<Object> getSellerStoreListByInfo(ErpSellerStoreEmpower storeEmpower) {
        ErpSellerStoreEmpowerBo bo = BeanUtil.copyProperties(storeEmpower,ErpSellerStoreEmpowerBo.class);
        List<ErpSellerStoreEmpower> storeEmpowerList = baseMapper.selectList(
                buildQueryWrapper(bo)
        );
        if (Objects.isNull(storeEmpowerList)){
            return R.fail(null);
        }else {
            return R.ok(storeEmpowerList);
        }

    }

    @Override
    public R<Object> selectEmpowerInUserName(List<String> collect) {
        List<ErpSellerStoreEmpower> storeEmpowerList = baseMapper.selectEmpowerInUserName(collect);
        if (Objects.isNull(storeEmpowerList)){
            return R.fail("未查找到需要店铺");
        }else {
            return R.ok(storeEmpowerList);
        }

    }

    @Override
    public ErpSellerStoreEmpower getCompriseDeleteById(Long id) {
        return baseMapper.selectAllById(id);
    }

    @Override
    public R<Object> bindShop(ErpSellerStoreEmpowerBo bo) {
        String storeUserName = bo.getStoreUserName();
        Long loginUserId = SecurityUtils.getUserId();
        ErpSellerStoreEmpower sellerStoreEmpower = baseMapper
                .selectOne(new LambdaQueryWrapper<ErpSellerStoreEmpower>()
                        .eq(ErpSellerStoreEmpower::getStoreUserName, storeUserName));
        if (sellerStoreEmpower == null) {
            return R.fail("未找到店铺");
        }
        Long bindUserId = sellerStoreEmpower.getUserId();
        if (bindUserId != null && !loginUserId.equals(bindUserId)) {
            return R.fail("店铺已在其他账号中绑定，请先解绑");
        }
        if (loginUserId.equals(bindUserId)) {
            return R.fail("您已绑定店铺，无需再次绑定");
        }
        sellerStoreEmpower.setUserId(loginUserId);
        int update = baseMapper.updateById(sellerStoreEmpower);
        if (update > 0) {
            // 添加绑定记录
            ErpShopBindRecord erpShopBindRecord = new ErpShopBindRecord();
            erpShopBindRecord.setStoreId(sellerStoreEmpower.getId());
            erpShopBindRecord.setStoreUserName(sellerStoreEmpower.getStoreUserName());
            erpShopBindRecord.setParentAgentId(sellerStoreEmpower.getParentAgentId());
            erpShopBindRecord.setParentBranchId(sellerStoreEmpower.getParentBranchId());
            erpShopBindRecord.setUserId(loginUserId);
            shopBindRecordMapper.insert(erpShopBindRecord);
            return R.ok();
        }

        return R.fail();
    }

    @Override
    public R<Object> unbindShop(String storeUserName) {
        ErpSellerStoreEmpower sellerStoreEmpower = baseMapper.selectOne(new LambdaQueryWrapper<ErpSellerStoreEmpower>().eq(ErpSellerStoreEmpower::getStoreUserName, storeUserName));
        if (sellerStoreEmpower == null) {
            return R.fail("找不到店铺");
        }
        sellerStoreEmpower.setUserId(null);
        int update = baseMapper.updateById(sellerStoreEmpower);
        return update > 0? R.ok() : R.fail();
    }

    @Override
    public R<Object> getNowStoreUserName() {
        List<String> storeUserNameLists = baseMapper.getNowStoreUserName();
        String join = String.join(",", storeUserNameLists.stream().map(String::valueOf).toArray(String[]::new));
        return R.ok(join);
    }
}
